//
//  ViewController.m
//  mutiThread
//
//  Created by admin on 17/4/9.
//  Copyright © 2017年 admin. All rights reserved.
//
#import "ViewController.h"
#import "KCImageData.h"
#import "secondViewViewController.h"
#import "ContactViewController.h"
#define ROW_COUNT 3
#define COLUMN_COUNT 6
#define ROW_HEIGHT 100
#define ROW_WIDTH ROW_HEIGHT
#define CELL_SPACING 10
#define CELL_WIDTH ([UIScreen mainScreen].bounds.size.width-(ROW_COUNT-1)*CELL_SPACING)/ROW_COUNT
#define CELL_HEIGHT (([UIScreen mainScreen].bounds.size.height-(COLUMN_COUNT-1)*CELL_SPACING )/COLUMN_COUNT)


@interface ViewController (){
    NSMutableArray *_imageViews;
    NSMutableArray *_imageNames;
    NSMutableArray *_threads;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.title=@"主页";
	[self.view setBackgroundColor:[UIColor whiteColor]];
	//[self.navigationController s:@"home"];
    //self.navigationItem.title=@"home";
    [self layoutUI];
}

#pragma mark 界面布局
-(void)layoutUI{
    //创建多个图片空间用于显示图片
    _imageViews=[NSMutableArray array];
//    for (int r=0; r<ROW_COUNT; r++) {
//        for (int c=0; c<COLUMN_COUNT; c++) {
//            UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING                           ), ROW_WIDTH, ROW_HEIGHT)];
//            imageView.contentMode=UIViewContentModeScaleAspectFit;
//            [self.view addSubview:imageView];
//            [_imageViews addObject:imageView];
//            
//        }
//    }
    for(int i=0;i<COLUMN_COUNT;i++){
        for (int j=0; j<ROW_COUNT; j++) {
            UIImageView *imagecell=[[UIImageView alloc]init];
            imagecell.frame=CGRectMake(j*(CELL_WIDTH+CELL_SPACING),
                                       i*(CELL_HEIGHT +CELL_SPACING ),
                                       CELL_WIDTH,
                                       CELL_HEIGHT);
            imagecell.contentMode=UIViewContentModeScaleAspectFit;
            [self.view addSubview:imagecell];
            [_imageViews addObject:imagecell];
            [_imageNames addObject:[NSString stringWithFormat:@"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg",(i*ROW_COUNT+j+1)%5]];
        }
    }
    
    //加载按钮
    UIButton *buttonStart=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    buttonStart.frame=CGRectMake(50, 500, 100, 25);
    [buttonStart setTitle:@"加载图片" forState:UIControlStateNormal];
    [buttonStart addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonStart];
	UIButton *toContactButton=[UIButton buttonWithType:UIButtonTypeRoundedRect] ;
	toContactButton.frame=CGRectMake(50, 600, 100, 25);
	[toContactButton setTitle:@"contact" forState:UIControlStateNormal];
	[self.view addSubview:toContactButton];
	[toContactButton addTarget:self action:@selector(btnToContact) forControlEvents:UIControlEventTouchUpInside];
    
    //停止按钮
    UIButton *buttonStop=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    buttonStop.frame=CGRectMake(160, 500, 100, 25);
    [buttonStop setTitle:@"停止加载" forState:UIControlStateNormal];
    [buttonStop addTarget:self action:@selector(stopLoadImage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonStop];
    
    //清除按钮
    UIButton *buttonclean=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    buttonclean.frame=CGRectMake(250, 500, 100, 25);
    [buttonclean setTitle:@"清除" forState:UIControlStateNormal];
    [buttonclean addTarget:self action:@selector(btnClean) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonclean];
    //跳转按钮
    UIButton * btntosecond=[UIButton buttonWithType:UIButtonTypeRoundedRect];;//[[UIButton alloc]init] ;//]WithFrame:CGRectMake(160, 700, 100, 25)];
                             btntosecond.frame=CGRectMake(160, 700, 100, 25);
    [btntosecond setTitle:@"跳转" forState:UIControlStateNormal];
    [btntosecond addTarget:self action:@selector(btnToSecondView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btntosecond];
    //创建图片链接
    _imageNames=[NSMutableArray array];
    //[_imageNames addObject:@
     for (int i=0; i<COLUMN_COUNT*ROW_COUNT; i++) {
        [_imageNames addObject:[NSString stringWithFormat:@"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg",i%5]];
    }
     }

#pragma mark 跳转到第二个页面
-(void)btnToSecondView{
    secondViewViewController * second =[[secondViewViewController alloc]init];
    //secondViewViewController * second =[[secondViewViewController alloc] initWithNibName:@"secondViewViewController" bundle:[NSBundle mainBundle]];
    //[self.navigationController pushViewController:second animated:YES];     [self.navigationController pushViewController:second animated:YES];
	// [self presentViewController:second animated:YES completion:nil];
	[self.navigationController pushViewController:second animated:YES];
    
}
#pragma mark 跳转到联系人界面
-(void)btnToContact{
 ContactViewController *contactVC=[[ContactViewController alloc] init];
	//[self presentViewController:contactVC animated:YES completion:nil];
	[self.navigationController pushViewController:contactVC animated:YES];
}
#pragma mark 将图片显示到界面
     -(void)updateImage:(KCImageData *)imageData{
         UIImage *image=[UIImage imageWithData:imageData.data];
         UIImageView *imageView= _imageViews[imageData.index];
         imageView.image=image;
     }
     
#pragma mark 请求图片数据
     -(NSData *)requestData:(int )index{
         //对于多线程操作建议把线程操作放到@autoreleasepool中
         @autoreleasepool {
             NSURL *url=[NSURL URLWithString:_imageNames[index]];
             NSData *data=[NSData dataWithContentsOfURL:url];
             
             return data;
         }
     }
     
#pragma mark 加载图片
     -(void)loadImage:(NSNumber *)index{
         int i=[index integerValue];
         
         NSData *data= [self requestData:i];
         
         
         NSThread *currentThread=[NSThread currentThread];
         
         //    如果当前线程处于取消状态，则退出当前线程
         if (currentThread.isCancelled) {
             NSLog(@"thread(%@) will be cancelled!",currentThread);
             [NSThread exit];//取消当前线程
         }
         NSLog(@"在线程:%@中加载第%d张照片",[NSThread currentThread],i);
         KCImageData *imageData=[[KCImageData alloc]init];
         imageData.index=i;
         imageData.data=data;
		 //[[NSOperationQueue mainQueue]addOperationWithBlock:^{
		 //    [self updateImage:imageData];
		 //}];
        //[self performSelectorOnMainThread:@selector(updateImage:) withObject:imageData waitUntilDone:YES];
		 dispatch_sync(dispatch_get_main_queue(), ^{
		 [self updateImage:imageData];
		 });
     }
     
#pragma mark 多线程下载图片
-(void)loadImageWithMultiThread{
    int count=ROW_COUNT*COLUMN_COUNT;
/*
 //创建操作队列
    NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
	for (int i=0; i<count; ++i) {
        NSBlockOperation *blockOperation=[NSBlockOperation blockOperationWithBlock:^{
            [self loadImage:[NSNumber numberWithInt:i]];
        }];
		[operationQueue addOperation:blockOperation];
    }
	
*/
/*
  串行队列
	dispatch_queue_t serialqueue= dispatch_queue_create("串行队列线程", DISPATCH_QUEUE_CONCURRENT);
	for (int i=0; i<count; ++i) {
		//异步执行队列任务
		dispatch_async(serialqueue, ^{
			[self loadImage:[NSNumber numberWithInt:i]];
		});
		
	}
*/
	dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
	//创建多个线程用于填充图片
	for (int i=0; i<count; ++i) {
		//异步执行队列任务
		dispatch_async(globalQueue, ^{
			[self loadImage:[NSNumber numberWithInt:i]];
		});
	}
}
-(void)mutiload{
    int count=ROW_COUNT*COLUMN_COUNT;
    _threads=[NSMutableArray arrayWithCapacity:count];
    
    //创建多个线程用于填充图片
    for (int i=0; i<count; ++i) {
        NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
        thread.name=[NSString stringWithFormat:@"myThread%i",i];//设置线程名称
        [_threads addObject:thread];
    }
    //循环启动线程
    for (int i=0; i<count; ++i) {
        NSThread *thread= _threads[i];
        [thread start];
    }
}
#pragma mark 清空图片
-(void)btnClean{
    for (int i=0; i<COLUMN_COUNT*ROW_COUNT; i++) {
        UIImageView *imageview=_imageViews[i];
        imageview.image=nil;
    }
}
#pragma mark 单线程下载
-(void)singleload{
    int count =ROW_COUNT*COLUMN_COUNT;
    for (int i=0; i<count; i++) {
            NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:_imageNames[i]]];
            UIImage *image=[UIImage imageWithData:imageData];
            UIImageView *imageview= _imageViews[i];//.image=image;
            imageview.image=image;
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"clickButtonAtIndex:%d",buttonIndex);
    if(buttonIndex==0){
        [self mutiload];
    }else{
        [self singleload];
    }
}
#pragma mark 停止加载图片
     -(void)stopLoadImage{
         for (int i=0; i<ROW_COUNT*COLUMN_COUNT; i++) {
             NSThread *thread= _threads[i];
             //判断线程是否完成，如果没有完成则设置为取消状态
             //注意设置为取消状态仅仅是改变了线程状态而言，并不能终止线程
             if (!thread.isFinished) {
                 [thread cancel];
                 
             }
         }
     }
     @end